<?php
namespace app\common\model;

class Area extends BaseModel{
	
	public function getNames($area_ids = ''){
		if(!$area_ids){
			return '';
		}
		$where['area_id'] = array('in', $area_ids);
		$name_arr = $this->where($where)->column('name');
		$name_str = implode(',', $name_arr);

		return $name_str ? $name_str : '';
	}
	/**
	 * 获取名称对应ID
	 * @param  string $name 区域名称
	 * @param  string $type 类型：0为国家，1为省份，2为城市，3为地区
	 */
	public function get_name_id($name = '', $type = ''){
		if(!$name){
			return 0;
		}
		if($type){
			$where['type'] = $type;
		}
		$where['name'] = $name;
		$area_id = $this->where($where)->value('area_id');

		return $area_id ? $area_id : 0;
	}
	/**
	 * IP地址转城市信息
	 * @param  string $ip IP地址
	 */
	public function ip2city($ip = '', $is_open = true){
		$ip = $ip ? $ip : request()->ip();
		// $ip       = '47.153.191.255';//加拿大
		// $ip       = '27.159.112.178';//厦门IP
		// $ip       = '120.42.46.138';//厦门IP
		// $ip       = '114.80.166.240';//上海IP
		// $ip       = '218.66.159.101';//泉州IP
		//获取IP城市名称
		import('IpLocation', EXTEND_PATH . '/net/', '.class.php');
		$ipLib    = new \IpLocation('QQWry-GBK.dat');
		$location = $ipLib->getlocation($ip); // 获取IP地址所在的位置
		$country_name = $location['country'];
		$country_name = iconv('gbk', 'utf8', $country_name);

		$str = str_replace(array('本机地址', '市', '局域网', 'IANA', '未知'), '', $country_name);
		$str = explode('省', $str);

		if(count($str) > 1){
			$ip_city_name = $str[1];
		}else{
			$ip_city_name = $str[0];
		}

		$city_info = '';
		if($ip_city_name){
			if($is_open){
				$where['is_open'] = 1;
			}
			$where['name'] = array('like', '%' . $ip_city_name . '%');
			$where['type'] = 2;//城市
			$city_info = $this->field('area_id city_id,name city_name,parent_id province_id')->where($where)->cache(true)->find();
			if($city_info){
				$city_info['province_name'] = $this->getNames($city_info['province_id']);
			}
		}
		if(!$city_info){
			$city_info['city_name']     = '北京';
			$city_info['city_id']       = 52;
			$city_info['province_name'] = '北京';
			$city_info['province_id']   = 2;
		}
		$city_info['ip'] = $ip;

		return $city_info;
	}
}